/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;
import DTO.Paciente;
import Model.conexionBD;
import java.awt.Image;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Jenny
 * http://www.forosdelweb.com/f127/subir-reducir-vista-previa-imagen-con-ajax-ejemplo-completo-702709/
 * 
 * http://www.forosdelweb.com/f127/subir-reducir-vista-previa-imagen-con-ajax-ejemplo-completo-702709/
 */
@WebServlet(name = " ServicioActualizaImagen", urlPatterns = {"/ServicioActualizaImagen"})
public class ServicioActualizaImagen extends HttpServlet {

    static String respuesta = "";
    String cedula;
    Blob b1 = null;
    String foto;
    String fi;
    String mimeImagen = null;
    FileInputStream fis;
    File file0;

    public static String getRespuesta() {
        return respuesta;
    }

    public static void setRespuesta(String respuesta) {
        ServicioRegistroPaciente.respuesta = respuesta;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        //mime = request.getParameter("mime");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        PrintWriter out = response.getWriter();
        try {

            int maxFileSize = 100000 * 1024;
            int maxMemSize = 100000 * 1024;
            ServletContext context = getServletConfig().getServletContext();
            String filePath = context.getRealPath("") + File.separator + "img" + File.separator;
   ;
            // Verify the content type
            String contentType = request.getContentType();
         if ((contentType.indexOf("multipart/form-data") >= 0)) {

                DiskFileItemFactory factory = new DiskFileItemFactory();
                // maximum size that will be stored in memory
                factory.setSizeThreshold(maxMemSize);
                // Location to save data that is larger than maxMemSize.
                factory.setRepository(new File(context.getRealPath("") + File.separator + "img"));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // maximum file size to be uploaded.
                upload.setSizeMax(maxFileSize);

                try {
                     // Parse the request to get file items.
                    List fileItems = upload.parseRequest(request);
                    Iterator i = fileItems.iterator();
                    while (i.hasNext()) {
                        FileItem fis = (FileItem) i.next();
                        if (!fis.isFormField()) {
                            b1= llenaBlob(fis);
                            getExtension(fis.getContentType());
                            llenarImagenes(filePath + fis.getName());
                        }else {
                            String name = fis.getFieldName();
                            if ("cedula".equals(name)) {
                                cedula = fis.getString();  
                            }
                        }
                    }
                    validaGeneral(request, response);
                } catch (Exception ex) {
                    System.out.println("Esta es la excepcion que tremendo ");
                    System.out.println(ex);
                }
         }
        } finally {
            out.close();
        }

    }

    public void llenarImagenes(String imagen) {
        this.foto = imagen;
    }

    public void getExtension(String valor) {
        this.mimeImagen = valor;
    }

    public Blob llenaBlob(FileItem b) throws SerialException, SQLException {
        return new SerialBlob(b.get());

    }
    public String extension(String vector) {
        String imagen = vector;
        String[] array = imagen.split("/");
        return array[1];
    }

    public boolean validaExtension(String ext) {
        boolean correcta = false;
        ArrayList<String> exts = new ArrayList<String>();
        exts.add("jpeg");
        exts.add("png");
        exts.add("gif");
        int cont = 0;
        while (exts.size() > cont) {
            if (exts.get(cont).equals(ext)) {
                correcta = true;
            }
            cont++;
        }

        return correcta;
    }

    public void validaGeneral(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean actualizado=false;
        try {

            conexionBD c = new conexionBD("root", "root", "SAPCOMED_DATABASE");
            c.setDirectorio_1(b1);
            c.setFile(fis);
            System.out.println("Desde el servlet: "+ b1);
            if (b1.length() > 0) {
                    if (validaExtension(this.extension(mimeImagen))) {
                      actualizado=c.actualizarFotoPac(Integer.parseInt(cedula), mimeImagen);
                      System.out.println(actualizado);
                     
                    }
            }
             request.getRequestDispatcher("HojaDatosPaciente.jsp?id="+cedula).forward(request, response); 
            
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(ServicioRegistroPaciente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
